package com.xshang.config;

import com.xshang.pojo.Configuration;
import com.xshang.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * parse： 解析映射配置文件 --> mappedStatement  ---> configuration里面的map集合
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parse(InputStream resourceAsStream) throws DocumentException {
        Document document = new SAXReader().read(resourceAsStream);
        Element rootElement = document.getRootElement();

        /*
             <select id="selectList" resultType="com.xshang.pojo.User">
                select * from user
             </select>
         */
        List<Element> selectList = rootElement.selectNodes("//select");
        // 获取标识namespace
        String namespace = rootElement.attributeValue("namespace");

        for (Element element : selectList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            // 去除前后空格获取select标签中的文本(SQL语句)
            String sql = element.getTextTrim();

            // 封装mappedStatement对象
            MappedStatement mappedStatement = new MappedStatement();

            String statementId = namespace + '.' + id;
            mappedStatement.setStatementId(statementId);

            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType("select");

            // 将封装好的MappedStatement对象 封装到configuration中
            configuration.getMappedStatementMap().put(statementId, mappedStatement);
        }

        return configuration;
    }
}
